package com.atguigu.gmall.pay.service.impl;


import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConfig;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.atguigu.gmall.feign.order.OrderFeignClient;
import com.atguigu.gmall.model.order.OrderDetail;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.mq.MqConst;
import com.atguigu.gmall.mq.to.OrderPaySkuDetaliTo;
import com.atguigu.gmall.mq.to.OrderPayedSuccessMessageTo;
import com.atguigu.gmall.pay.config.AppAlipayConfig;
import com.atguigu.gmall.pay.service.PayService;
import com.atguigu.gmall.pay.vo.PayParamVo;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.bouncycastle.voms.VOMSAttribute;
import org.checkerframework.checker.units.qual.A;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class PayServiceImpl implements PayService {

    @Autowired
    AlipayClient alipayClient;

    @Autowired
    AppAlipayConfig alipayConfig;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    OrderFeignClient orderFeignClient;





    public String payOrder(PayParamVo vo) throws Exception {
        //1、创建一个支付请求
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(alipayConfig.getReturn_url());
        alipayRequest.setNotifyUrl(alipayConfig.getNotify_url());

        //2、设置支付请求的请求体详情
        String json = new ObjectMapper().writeValueAsString(vo);
        alipayRequest.setBizContent(json);

        //3、调用支付宝的远程支付功能
        String result = alipayClient.pageExecute(alipayRequest).getBody();


          //代表的是支付宝返回的二维码支付页

        //返回支付宝的二维码支付页
        return result;
    }

    /**
     * 检查订单是否支付
     * @param outTradeNo
     * @return
     */
    @Override
    public Boolean queryOrderStatus(String outTradeNo) throws AlipayApiException, JsonProcessingException {

        //1、设置请求参数
        AlipayTradeQueryRequest alipayRequest = new AlipayTradeQueryRequest();

        //请二选一设置
        Map<String,String> map = new HashMap<>();
        map.put("out_trade_no",outTradeNo);
        //map改写成字符串
        String asString = new ObjectMapper().writeValueAsString(map);

        alipayRequest.setBizContent(asString);

        //请求
        AlipayTradeQueryResponse response = alipayClient.execute(alipayRequest);
        if ("10000".equals(response.getCode())&&response.getTradeStatus().equals("TRADE_SUCCESS")){
            //支付成功
            return true;
        }


        return false;
    }

    @Override
    public void sendPaySuccessMessage(String out_trade_no) throws JsonProcessingException {


        //TODO 2、给队列发送的内容； JSON串
        OrderInfo orderInfo = orderFeignClient.getOrderInfoWithDetailsByOutTradeNo(out_trade_no);

        //1、准备mq消息内容 封装订单信息
        OrderPayedSuccessMessageTo message = new OrderPayedSuccessMessageTo();
        BeanUtils.copyProperties(orderInfo,message);

        message.setOrderId(orderInfo.getId());
        message.setOrderBody(orderInfo.getOrderDetailList().get(0).getSkuName());
        message.setPaymentWay("2");//在线支付

        //2、封装订单的所有商品信息
        List<OrderPaySkuDetaliTo> details = new ArrayList<>();
        List<OrderDetail> orderDetailList = orderInfo.getOrderDetailList();
        for (OrderDetail detail : orderDetailList) {
            OrderPaySkuDetaliTo detaliTo = new OrderPaySkuDetaliTo();
            BeanUtils.copyProperties(detail,detaliTo);
            details.add(detaliTo);
        }

        message.setDatails(details);


        //TODO 1、队列名： query_ware_stock  需要知道哪个交换机用哪个路由键绑定这个对象

        /**
         * @RabbitListener(bindings = @QueueBinding(
         *             value = @Queue(value = MqConst.QUEUE_WARE_STOCK, durable = "true"),
         *             exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_WARE_STOCK, type = ExchangeTypes.DIRECT, durable = "true"),
         *             key = {MqConst.ROUTING_WARE_STOCK}
         *     ))
         */

        String string = new ObjectMapper().writeValueAsString(message);
        //给库存发送了消息
        rabbitTemplate.convertAndSend(MqConst.EXCHANGE_DIRECT_WARE_STOCK,MqConst.ROUTING_WARE_STOCK);

    }
}
